﻿Imports MySql.Data.MySqlClient
Public Class MySqlHandler
    Private mconf As MySqlConfiguration
    Private ler As String
    Private mu As MySqlUtilities
    Private Shared instance As MySqlHandler
    Private cx As MySqlConnection
    Private log As ActivityLogger
    Private errcode As Int16
    Private mappingerror As String
    Private Sub New()
        mysqlconf = New MySqlConfiguration
        mu = New MySqlUtilities(mysqlconf)
        log = ActivityLogger.getInstance
    End Sub

    Public Property mysqlconf As MySqlConfiguration
        Get
            Return mconf
        End Get
        Set(ByVal value As MySqlConfiguration)
            mconf = value
        End Set
    End Property

    Public Property Errors As String
        Get
            Return ler
        End Get
        Set(ByVal value As String)
            ler = value
        End Set
    End Property
    Public Function testConnection() As Boolean
        Return False
    End Function
    Public Function getConnection() As MySqlConnection
        If (openConnection()) Then Return cx
        Return Nothing
    End Function
    Public Function openConnection() As Boolean
        If (IsNothing(cx)) Then
            Dim str As String = mu.getConnectionString(True)
            cx = New MySqlConnection(str)
        End If
        If (cx.State = ConnectionState.Closed) Then
            If (Not doOpenConnection(cx)) Then Return False
        End If
        Return True
    End Function
    Public Function getConnection(ByVal str As String) As MySqlConnection
        Dim lc As MySqlConnection = New MySqlConnection(str)
        If (Not doOpenConnection(lc)) Then Return Nothing
        Return lc
    End Function

    Private Function doOpenConnection(ByRef lc As MySqlConnection)
        Try
            lc.Open()
        Catch ex As MySqlException
            errcode = ex.Number
            Select Case ex.Number
                Case MySqlErrorCode.UnknownDatabase
                    Errors = "Database " + lc.Database + " not found"
                Case MySqlErrorCode.AccessDenied
                    Errors = "Bad Username or Password "
                Case MySqlErrorCode.DatabaseAccessDenied
                    Errors = "Access to Database " + lc.Database + " denied"
                Case Else
                    Errors = "Unknow error:" + ex.Message
            End Select
            doLog("Error Occured [OpenConnection]:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return False
        End Try
        Return True
    End Function
   
    Public Function closeConnection() As Boolean
        Try
            If (Not IsNothing(cx)) Then cx.Close()
        Catch ex As MySqlException
            doLog("Error Occured [closeConnection]:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return False
        End Try
        Return True
    End Function
    Public Function insertQuery(ByVal querystring As String)
        Errors = ""
        Dim ret As Integer = 0
        Try
            ret = MySqlHelper.ExecuteNonQuery(cx, querystring)
        Catch ex As MySqlException
            doLog("Error Occured [insertQuery]:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Errors = ex.Message
            errcode = ex.Number
        End Try

        Return ret
    End Function
    Public Function executeQuery(ByVal sql As String, ByVal param As Hashtable, Optional ByRef lc As MySqlConnection = Nothing) As Boolean
        doLog("Executing parameterised query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Errors = ""
        errcode = 0
        If (IsNothing(lc)) Then
            If (IsNothing(cx)) Then
                If (Not openConnection()) Then Return Nothing
            End If
            lc = cx
        End If
        Try
            Dim cmd As MySqlCommand = New MySqlCommand(sql, lc)
            For Each key As String In param.Keys
                Dim p As New MySqlParameter(key, param.Item(key))
                cmd.Parameters.Add(p)
            Next
            cmd.ExecuteNonQuery()
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number

            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return False
        End Try
        doLog("Executing datatable query sucessfull", ActivityLoggerConf.LOGLEVEL_INFO)
        Return True
    End Function

    Public Function executeQuery(ByVal sql As String) As Boolean
        doLog("Executing query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim i As Integer = 0
        Try
            i = MySqlHelper.ExecuteNonQuery(getConnection, sql)
        Catch ex As MySqlException
            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Errors = "Execption occured when executin query" + vbCrLf + "Query:" + sql + vbCrLf + "Error:" + ex.Message
            Return False
        End Try
        doLog("Query successfully executed " + i.ToString, ActivityLoggerConf.LOGLEVEL_INFO)
        Return True
    End Function
    Public Function executeQuery(ByVal lc As MySqlConnection, ByVal sql As String) As Boolean
        doLog("Executing query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim i As Integer = 0
        Try
            i = MySqlHelper.ExecuteNonQuery(lc, sql)
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number
            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return False
        End Try
        doLog("Query successfully executed " + i.ToString, ActivityLoggerConf.LOGLEVEL_INFO)
        Return True
    End Function
    Private Function executeDataTable(ByVal sql As String, ByVal table As String, Optional ByRef lc As MySqlConnection = Nothing) As DataTable
        doLog("Executing datatable query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Errors = ""
        errcode = 0
        If (IsNothing(lc)) Then
            If (IsNothing(cx)) Then
                If (Not openConnection()) Then Return Nothing
            End If
            lc = cx
        End If
        Dim r As DataTable
        Try
            Dim dts As DataSet = MySqlHelper.ExecuteDataset(lc, sql)
            If (IsNothing(dts)) Then Return Nothing
            r = dts.Tables(table)
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number

            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return Nothing
        End Try
        doLog("Executing datatable query sucessfull", ActivityLoggerConf.LOGLEVEL_INFO)
        Return r

    End Function
    Private Function executeDataRow(ByVal sql As String, Optional ByRef lc As MySqlConnection = Nothing) As DataRow
        doLog("Executing datarow query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim r As DataRow = Nothing
        If (IsNothing(lc)) Then
            If (IsNothing(cx)) Then
                If (Not openConnection()) Then Return Nothing
            End If
            lc = cx
        End If
        Try
            r = MySqlHelper.ExecuteDataRow(lc.ConnectionString, sql)
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number
            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return Nothing
        End Try
        doLog("Executing datarow query sucessfull", ActivityLoggerConf.LOGLEVEL_INFO)
        Return r
    End Function
    Public Function getDbInfo(Optional ByRef lc As MySqlConnection = Nothing) As MysqlDbInfo
        If (IsNothing(lc)) Then lc = getConnection()
        Dim dbi As MysqlDbInfo = mu.getMySqlServerInfo(lc)
        Return dbi
    End Function
    Private Function executeReader(ByVal sql As String, Optional ByRef lc As MySqlConnection = Nothing) As MySqlDataReader
        doLog("Executing reader query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim r As MySqlDataReader = Nothing
        If (IsNothing(lc)) Then
            If (IsNothing(cx)) Then
                If (Not openConnection()) Then Return Nothing
            End If
            lc = cx
        End If
        Try
            r = MySqlHelper.ExecuteReader(lc, sql)
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number
            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return Nothing
        End Try
        doLog("Executing reader query sucessfull", ActivityLoggerConf.LOGLEVEL_INFO)
        Return r
    End Function
    Private Function resetConnection() As Boolean
        closeConnection()
        cx = Nothing
        openConnection()
        Return True
    End Function
    Public Shared Function getInstance() As MySqlHandler
        If (IsNothing(instance)) Then instance = New MySqlHandler
        Return instance
    End Function
    Public Function installDatabase() As Boolean
        doLog("Installing Database " + mysqlconf.mysql_database, ActivityLoggerConf.LOGLEVEL_OPERATION)
        Dim lc As MySqlConnection = getConnection(mu.getConnectionString(False))
        If (IsNothing(lc)) Then
            Errors = "unable to connect to Mysql database due to " + Errors
            Return False
        End If
        Dim sql = "create database " + mysqlconf.mysql_database
        If (Not executeQuery(lc, sql)) Then
            Errors = "unable to create " + mysqlconf.mysql_database + " due to" + Errors
            Return False
        End If
        lc.ChangeDatabase(mysqlconf.mysql_database)

        resetConnection()
        If (Not executeQuery(mu.createTableSql(New ewindt.DtSyncLogDataTable))) Then
            If (Not errcode = MySqlErrorCode.TableExists) Then
                Errors = "unable to create SyncLog table due to" + Errors
                Return False
            End If
        End If
        'insert installation time
        installTable()
        doLog("Installing Database " + mysqlconf.mysql_database + " done", ActivityLoggerConf.LOGLEVEL_OPERATION)
        Return True
    End Function
    Private Function installTable(Optional ByRef lc As MySqlConnection = Nothing) As Boolean
        If (IsNothing(lc)) Then lc = cx
        'install mapping table
        doLog("Installing mapping tables " + mysqlconf.mysql_database, ActivityLoggerConf.LOGLEVEL_OPERATION)
        If (Not executeQuery(lc, mu.createTableSql(New ewindt.DtTableMappingDataTable))) Then
            If (Not errcode = MySqlErrorCode.TableExists) Then
                Errors = "unable to create Mappings tables due to" + Errors

                Return False
            End If
        End If
        If (Not executeQuery(lc, mu.createTableSql(New ewindt.DtColumnMappingDataTable))) Then
            If (Not errcode = MySqlErrorCode.TableExists) Then
                Errors = "unable to create Mappings tables due to" + Errors
                Return False
            End If
        End If
        doLog("Installing mapping tables dones" + mysqlconf.mysql_database, ActivityLoggerConf.LOGLEVEL_OPERATION)
        Return True
    End Function
    Public Function getTablesMapping() As ewindt.DtTableMappingDataTable
        Dim dt As New ewindt.DtTableMappingDataTable
        Dim sql As String = "select * from " + dt.TableName + " where " + dt.mapstateColumn.ColumnName + "=1"
        Dim r As MySqlDataReader = executeReader(sql)
        If (Not IsNothing(r)) Then
            Try
                dt.Load(r)
            Catch ex As Exception
                MsgBox("error" + ex.Message)
                Return Nothing
            End Try
        End If
        Return dt
    End Function
    Public Function getColumnMapping() As ewindt.DtColumnMappingDataTable
        Dim dt As New ewindt.DtColumnMappingDataTable
        Dim sql As String = "select * from " + dt.TableName
        Dim r As MySqlDataReader = executeReader(sql)
        If (Not IsNothing(r)) Then
            Try
                dt.Load(r)
            Catch ex As Exception
                MsgBox("error" + ex.Message)
                Return Nothing
            End Try
        End If
        Return dt
    End Function
    Private Sub doLog(ByVal msg As String, ByVal svt As String)
        log.log(commons.MOD_MYSQLHANDLER, msg, svt)
    End Sub

    Public Function addTableMapping(ByVal tablename As String, ByVal winccarchive As String) As ewinsync.ewindt.DtTableMappingRow
        Dim dt As New ewindt.DtTableMappingDataTable
        Dim r As ewindt.DtTableMappingRow = dt.NewDtTableMappingRow
        Dim sql As String = "insert into " + dt.TableName + " (" + dt.mysqltablenameColumn.ColumnName + "," + dt.wincctablenameColumn.ColumnName + "," + dt.mapstateColumn.ColumnName + ") values "
        sql = sql + " ('" + tablename + "','" + winccarchive + "',1)"
        Dim ret As Integer = insertQuery(sql)
        If (ret <= 0) Then Return Nothing
        r.mapstate = 1
        r.mysqltablename = tablename
        r.wincctablename = winccarchive
        r.id = ret
        Return r
    End Function

    Public Function deleteTableMapping() As Boolean
        Return True
    End Function
    Public Function deactivateColumnMapping(ByVal id As Integer) As Boolean
        Dim dt As New ewindt.DtColumnMappingDataTable
        Dim sql As String = "update " + dt.TableName + " set " + dt.idtablemappingColumn.ColumnName + "=" + id.ToString
        Dim ret = executeQuery(sql)
        Return ret
    End Function
    Public Function updateColMapping(ByVal id As Integer, ByVal mysqlcol As String, ByVal wcname As String, ByVal wcid As Integer) As Boolean
        Dim dt As New ewindt.DtColumnMappingDataTable
        Dim sql As String = "update " + dt.TableName + " set " + dt.importedColumn.ColumnName + "=true, " + dt.mycolnameColumn.ColumnName + "='" + mysqlcol.Trim + "', " + dt.wincolnameColumn.ColumnName + "='" + MySqlHelper.EscapeString(wcname.Trim) + "', " + dt.wincolidColumn.ColumnName + "=" + wcid.ToString + " where " + dt.idColumn.ColumnName + "=" + id.ToString
        Dim ret = executeQuery(sql)
        Return ret
    End Function
    Public Function addColMapping(ByVal mapid As Integer, ByVal mysqlcol As String, ByVal wcname As String, ByVal wcid As Integer) As Boolean
        Dim dt As New ewindt.DtColumnMappingDataTable
        Dim sql As String = "insert into " + dt.TableName + "(" + dt.idtablemappingColumn.ColumnName + "," + dt.mycolnameColumn.ColumnName + ", " + dt.wincolnameColumn.ColumnName + "," + dt.importedColumn.ColumnName + "," + dt.wincolidColumn.ColumnName + ") values ("
        sql = sql + "" + mapid.ToString + ",'" + mysqlcol.Trim + "','" + wcname.Trim + "',true," + wcid.ToString + ")"
        Dim ret = executeQuery(sql)

        Return ret
    End Function
    Public Function checkAnCompareMapping(ByVal tablemap As ewindt.DtTableMappingDataTable, ByVal colmap As ewindt.DtColumnMappingDataTable) As Boolean
        'check tag loggin mapping
        doLog("Cheking mapping tables", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim haserror As Boolean = False
        Dim dbi As MysqlDbInfo = mu.getMySqlServerInfo(getConnection)
        For Each r As ewindt.DtTableMappingRow In tablemap.Rows
            If (r.wincctablename = WinccConfig.ARCHIVE) Then
                If (Not checkTagLogginMapping(r, dbi, colmap)) Then
                    haserror = True
                End If
            Else
                If (Not checkAlarmLogginMapping(r, dbi, colmap)) Then
                    haserror = True
                End If
            End If
        Next
        If (haserror) Then Errors = mappingerror
        Return Not haserror
    End Function
    Private Function checkTagLogginMapping(ByRef r As ewindt.DtTableMappingRow, ByRef dbi As MysqlDbInfo, ByVal colmap As ewindt.DtColumnMappingDataTable) As Boolean
        Dim haserror As Boolean = False
        Dim tablename As String = r.mysqltablename
        Dim svrtable As MysqlTableInfo = dbi.Table(tablename)
        If (IsNothing(svrtable)) Then
            'if not exist->create
            Dim str As String = createMappingTable(r, colmap)
            If (Not String.IsNullOrEmpty(str)) Then
                mappingerror = mappingerror + vbCrLf + str
            End If
        Else
            Dim filter = colmap.idtablemappingColumn.ColumnName + "=" + r.id.ToString
            Dim lrow() As ewindt.DtColumnMappingRow = colmap.Select(filter)
            If (lrow.Length > 0) Then
                For Each row As ewindt.DtColumnMappingRow In lrow
                    Dim colname = row.mycolname
                    Dim svrcol As MysqlColInfo = svrtable.getColumn(colname)
                    If (IsNothing(svrcol)) Then
                        If (svrtable.TotalRows <= 0) Then
                            'if the table is empty simply drop table and recreate all the table
                            dropTable(tablename)
                            Dim str As String = createMappingTable(r, colmap)
                            If (Not String.IsNullOrEmpty(str)) Then
                                mappingerror = mappingerror + vbCrLf + str
                            End If
                            Exit For
                        Else
                            'if not empty do cumulative error and exit
                            Dim em As String = "Table " + tablename + " exist but column" + colname + " is missing"
                            doLog(em, ActivityLoggerConf.LOGLEVEL_INFO)
                            mappingerror = mappingerror + vbCrLf + em
                            haserror = True
                        End If
                    Else
                        'check if the same type
                        'must be a double...
                        If (Not svrcol.ColumnType = MySqlDbType.Double) Then
                            Dim em As String = "Table " + tablename + " exist but column" + colname + " has not the correct type"
                            doLog(em, ActivityLoggerConf.LOGLEVEL_INFO)
                            mappingerror = mappingerror + vbCrLf + em
                            haserror = True
                            Exit For
                        End If
                    End If
                Next
            End If
        End If
        Return Not haserror
    End Function
    Private Function checkAlarmLogginMapping(ByRef r As ewindt.DtTableMappingRow, ByRef dbi As MysqlDbInfo, ByVal colmap As ewindt.DtColumnMappingDataTable) As Boolean
        Dim haserror As Boolean = False
        Dim tablename As String = r.mysqltablename
        Dim svrtable As MysqlTableInfo = dbi.Table(tablename)
        If (IsNothing(svrtable)) Then
            'if not exist->create
            Dim str As String = createAlarmMappingTable(r, colmap)
            If (Not String.IsNullOrEmpty(str)) Then
                mappingerror = mappingerror + vbCrLf + str
            End If
        Else
            Dim filter = colmap.idtablemappingColumn.ColumnName + "=" + r.id.ToString
            Dim lrow() As ewindt.DtColumnMappingRow = colmap.Select(filter)
            If (lrow.Length > 0) Then
                For Each row As ewindt.DtColumnMappingRow In lrow
                    Dim colname = row.mycolname
                    Dim svrcol As MysqlColInfo = svrtable.getColumn(colname)
                    If (IsNothing(svrcol)) Then
                        If (svrtable.TotalRows <= 0) Then
                            'if the table is empty simply drop table and recreate all the table
                            dropTable(tablename)
                            Dim str As String = createMappingTable(r, colmap)
                            If (Not String.IsNullOrEmpty(str)) Then
                                mappingerror = mappingerror + vbCrLf + str
                            End If
                            Exit For
                        Else
                            'if not empty do cumulative error and exit
                            Dim em As String = "Table " + tablename + " exist but column" + colname + " is missing"
                            doLog(em, ActivityLoggerConf.LOGLEVEL_INFO)
                            mappingerror = mappingerror + vbCrLf + em
                            haserror = True
                        End If
                    Else
                        'check if the same type
                        'must be a double...
                        If (Not svrcol.ColumnType = MySqlDbType.Double) Then
                            Dim em As String = "Table " + tablename + " exist but column" + colname + " has not the correct type"
                            doLog(em, ActivityLoggerConf.LOGLEVEL_INFO)
                            mappingerror = mappingerror + vbCrLf + em
                            haserror = True
                            Exit For
                        End If
                    End If
                Next
            End If
        End If
        Return Not haserror
    End Function
    Private Function createMappingTable(ByVal r As ewindt.DtTableMappingRow, ByVal colmap As ewindt.DtColumnMappingDataTable) As String
        doLog("Table " + r.mysqltablename + " not found. Creating table", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim ret As Boolean = createMapValueHolder(r.mysqltablename, r.id, colmap)
        If (Not ret) Then
            doLog("Table " + r.mysqltablename + " not created: " + Errors, ActivityLoggerConf.LOGLEVEL_INFO)
            Return Errors
        Else
            doLog("Table " + r.mysqltablename + " created", ActivityLoggerConf.LOGLEVEL_INFO)

        End If
        Return ""
    End Function
    Private Function createAlarmMappingTable(ByVal r As ewindt.DtTableMappingRow, ByVal colmap As ewindt.DtColumnMappingDataTable) As String
        doLog("Table " + r.mysqltablename + " not found. Creating table", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim ret As Boolean = createMapValueHolder(r.mysqltablename, r.id, colmap)
        If (Not ret) Then
            doLog("Table " + r.mysqltablename + " not created: " + Errors, ActivityLoggerConf.LOGLEVEL_INFO)
            Return Errors
        Else
            doLog("Table " + r.mysqltablename + " created", ActivityLoggerConf.LOGLEVEL_INFO)

        End If
        Return ""
    End Function
    Private Function dropTable(ByVal tablename As String) As Boolean
        doLog("Dropping Table " + tablename, ActivityLoggerConf.LOGLEVEL_INFO)
        Dim sql As String = "drop " + tablename
        executeQuery(sql)
        doLog("Table " + tablename + " dropped", ActivityLoggerConf.LOGLEVEL_INFO)
        Return True
    End Function

    Private Function createMapValueHolder(ByVal tablename As String, ByVal tableid As Integer, ByVal colmap As ewindt.DtColumnMappingDataTable) As Boolean
        Dim filter As String = colmap.idtablemappingColumn.ColumnName + "=" + tableid.ToString
        Dim rows() As ewindt.DtColumnMappingRow = colmap.Select(filter)

        Dim table As DataTable = New DataTable(tablename)
        Dim id As DataColumn = mu.getAutoIncrementField("id")
        table.Columns.Add(id)
        table.PrimaryKey = {id}
        table.Columns.Add(mu.getDataColumn("recorddate", MySqlDbType.DateTime))
        table.Columns.Add(mu.getDataColumn("importedat", MySqlDbType.DateTime))
        table.Columns.Add(mu.getDataColumn("issync", MySqlDbType.Int32))
        table.Columns.Add(mu.getDataColumn("syncat", MySqlDbType.DateTime))
        For Each row As ewindt.DtColumnMappingRow In rows
            table.Columns.Add(mu.getDataColumn(row.mycolname, MySqlDbType.Double))
        Next
        Dim sql = mu.createTableSql(table)
        Dim ret As Boolean = executeQuery(sql)
        Return ret
    End Function
    Private Function executeScalar(ByVal sql As String, Optional ByRef lc As MySqlConnection = Nothing) As Object
        doLog("Executing scalar query [" + sql + "]", ActivityLoggerConf.LOGLEVEL_INFO)
        Dim r As Object = Nothing
        If (IsNothing(lc)) Then
            If (IsNothing(cx)) Then
                If (Not openConnection()) Then Return Nothing
            End If
            lc = cx
        End If
        Try
            r = MySqlHelper.ExecuteScalar(lc, sql)
        Catch ex As MySqlException
            Errors = ex.Message
            errcode = ex.Number
            doLog("Exception occured:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return Nothing
        End Try
        doLog("Executing scalar query sucessfull", ActivityLoggerConf.LOGLEVEL_INFO)
        'If (IsDBNull(r)) Then Return Nothing
        Return r

    End Function

    Public Function getLastWinccSync() As Object
        Dim t As New ewindt.DtSyncLogDataTable
        Dim sql As String = "select " + t.lastwinccsyncColumn.ColumnName + " from " + t.TableName + " where id=1"
        Dim r As Object = executeScalar(sql)
        If (IsNothing(r)) Then
            prepareSyncLog()
        ElseIf (IsDBNull(r)) Then
            Return Nothing
            ' Return Nothing
        End If

        Return r
    End Function
    Private Sub prepareSyncLog()
        Dim t As New ewindt.DtSyncLogDataTable
        Dim sql As String = "insert into " + t.TableName + " (id) values (1)"
        executeQuery(sql)
    End Sub
    Public Function updateLastWinccSync(ByVal ls As DateTime) As Boolean
        Dim t As New ewindt.DtSyncLogDataTable
        Dim sql As String = "update " + t.TableName + " set " + t.lastwinccsyncColumn.ColumnName + "=@ls where id=1"
        Dim p As New Hashtable
        p.Add("ls", ls)
        executeQuery(sql, p)
        Return True
    End Function
    Public Function recordTagValue(ByRef table As ewindt.DtTableMappingRow, ByRef cols() As ewindt.DtColumnMappingRow, ByRef wsort As WinCcDataSorter) As Boolean
        doLog("Starting tag value recording for " + table.mysqltablename, ActivityLoggerConf.LOGLEVEL_OPERATION)
        Dim errcount As Integer = 0
        Dim datarecorded As Integer = 0
        Dim sql = mu.getParameterisedSql(table, cols)
        Dim data As Hashtable = wsort.getData

        For Each rd As DateTime In data.Keys
            Dim param As New Hashtable
            param.Add("recorddate", rd)
            param.Add("importedat", Now)
            Dim row As Hashtable = data.Item(rd)
            For Each col As ewindt.DtColumnMappingRow In cols
                Dim key As String = col.wincolname
                Dim value As Object = row.Item(key)
                param.Add(col.mycolname, value)
            Next
            If (Not executeQuery(sql, param)) Then errcount = errcount + 1
            datarecorded = datarecorded + 1
        Next
        doLog("Ttag value recording for " + table.mysqltablename + " done with " + datarecorded.ToString + " data to records and " + errcount.ToString + "error(s)", ActivityLoggerConf.LOGLEVEL_OPERATION)
        Return True
    End Function

End Class
